﻿using AutoMapper;
using General.Core.Config;
using General.Core.Data;
using General.Entities.Data;
using General.Entities.Models;
using General.Entities.ViewData.Authority;
using General.Services.Dictionary;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace General.Services.Authority
{
    public class AuthorityService : IAuthorityService
    {
        private readonly IRepository<tc_authority> tc_AuthorityRepository;
        private readonly IMemoryCache memoryCache;
        private readonly IMapper mapper;

        public AuthorityService(IRepository<tc_authority> tc_authorityRepository,
            IMemoryCache memoryCache,
            IMapper mapper)
        {
            tc_AuthorityRepository = tc_authorityRepository;
            this.memoryCache = memoryCache;
            this.mapper = mapper;
        }


        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> AddInfo(AuthorityModel model)
        {
            var data = mapper.Map<tc_authority>(model);
            data.parentId = model.select== null||model.select == -1 ? -1: model.select;
            data.createTime = DateTime.Now;
            data.updateTime = DateTime.Now;

            await GetDataWriteMemory();
            return await tc_AuthorityRepository.insertAsync(data);
        }


        /// <summary>
        /// 获取所有角色数据写入内存
        /// </summary>
        /// <returns></returns>
        public async Task GetDataWriteMemory()
        {
            var res = await tc_AuthorityRepository.GetAllAsync(x=>x.isMenu==1).OrderBy(x => x.id).ToListAsync();
            memoryCache.Set(GobalConfig.SYSTEM_MENULISTMEMORYKEY_STRING, JsonHelper.Serialize(res));
        }

        /// <summary>
        /// 判断上级是否为菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> IsMenuById(int id)
        {
            var data = await tc_AuthorityRepository.getByIdAsync(id);
            if (data==null||data.isMenu == 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 判断标识是否已存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> IsHasAuthority(string name,int? id = null)
        {
            if (id ==null)
            {
                return await tc_AuthorityRepository.IsExistAsync(x => x.authority == name);
            }
            var model = await tc_AuthorityRepository.GetAsync(x=>x.id == id);
            return await tc_AuthorityRepository.IsExistAsync(x => x.authority != model.authority && x.authority == name);
        }

        /// <summary>
        /// 后台编辑数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<int> EditInfo(AuthorityModel model)
        {
            var data = mapper.Map<tc_authority>(model);
            data.parentId = model.select == null || model.select == -1 ? -1 : model.select;
            data.updateTime = DateTime.Now;
            Expression<Func<tc_authority, object>>[] updatedProperties = {
                    p => p.updateTime,p=>p.isMenu,p=>p.menuIcon,p=>p.parentId,
                    p=>p.authorityName,p=>p.menuUrl,p=>p.authority,p=>p.orderNumber,p=>p.isUse
                };


            await GetDataWriteMemory();
            return await tc_AuthorityRepository.UpdateByFieldsAsync(data, updatedProperties);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteInfo(string ids)
        {
            var arr = ids.Split(",", StringSplitOptions.RemoveEmptyEntries);
            List<tc_authority> list = new List<tc_authority>();
            foreach (var item in arr)
            {
                list.Add(new tc_authority() { id = Convert.ToInt32(item) });
            }

            await GetDataWriteMemory();
            return await tc_AuthorityRepository.DeleteListByFieldsAsync(list);
        }

        /// <summary>
        /// 获取全部可用状态数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<tc_authority>> GetIsUseData()
        {
            return await tc_AuthorityRepository.GetAllAsync(x=>x.isUse==1).OrderBy(x=>x.orderNumber).ToListAsync();
        }

        /// <summary>
        /// 获取列表信息    
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<AdminResult> GetList(string authorityName, string menuUrl, string authority)
        {
            AdminResult result = new AdminResult();
            var query = tc_AuthorityRepository.Table.Where(x => !string.IsNullOrWhiteSpace(authorityName) ? x.authorityName.Contains(authorityName) : true && !string.IsNullOrWhiteSpace(menuUrl) ? x.menuUrl.Contains(menuUrl) : true && !string.IsNullOrWhiteSpace(authority) ? x.authority.Contains(authority) : true).OrderBy(x=>x.orderNumber);
            result.count = await query.CountAsync();
            result.data = await query.ToListAsync();
            result.code = 0;
            return result;
        }
    }
}
